import React from 'react';
import * as THREE from 'three';
import Scene from '../Scene';
import style from '../FrozenStation.css';
let windLeaves = [], envMap;
export default class Room {
    constructor(){
        this.scene = new Scene();
        this.canvasScene = this.scene.scene;
        this.resources = this.scene.resources;
        this.room = this.resources.items.room;
        this.renderer = this.scene.renderer;
        this.time = this.scene.time;
        this.sizes = this.scene.sizes;
        this.camera = this.scene.camera.perspectiveCamera;
        // this.setModel2();
        this.setModel();
        this.setAnimation();
        // 测试材质特性
        // this.setMtl();
    }
    setModel2(){
        let that = this;        
        // 场景中的所有Mesh都添加阴影设置
        let pmremGenerator = new THREE.PMREMGenerator(this.renderer.renderer);
        new THREE.TextureLoader().load( '/models/equirectangular.png', function ( texture ) {
            texture.mapping = THREE.EquirectangularReflectionMapping;
            texture.colorSpace = THREE.SRGBColorSpace;
            envMap = pmremGenerator.fromEquirectangular( texture );
            that.room.scene.children.forEach(child=>{
                if ( child.name.includes('扇叶')){
                    objs.push(child);
                }
                if ( child.name === 'water-bump005' ) {
                    // that.setAlarm(child);
                }
                if ( child instanceof THREE.Group ) {
                    child.children.forEach(sub=>{
                        that.handleMtl(sub);
                    });
                } else {
                    that.handleMtl(child);
                }
            })
            that.canvasScene.add(that.room.scene);               
        } );
    }
    setModel(){
        console.log(this.resources);
        let group = this.resources.items.room.scene;
        let tex1 = this.resources.items['bake-1'];
        tex1.flipY = false;
        tex1.encoding = THREE.sRGBEncoding;
        let tex2 = this.resources.items['bake-2'];
        tex2.flipY = false;
        tex2.encoding = THREE.sRGBEncoding;
        this.resources.items['flow'].wrapS = THREE.RepeatWrapping;
        this.resources.items['flow'].wrapT = THREE.RepeatWrapping;
        this.resources.items['flow'].flipY = false;
        this.resources.items['flow'].encoding = THREE.sRGBEncoding;
    
        let mtl1 = new THREE.MeshBasicMaterial({
            map:tex1,
            side:THREE.DoubleSide
        });
        let mtl2 = new THREE.MeshBasicMaterial({
            map:tex2,
            side:THREE.DoubleSide
        });
        let tubeMtl = new THREE.MeshBasicMaterial({
            color:0xafafaf,
            // map:this.resources.items['flow'],
            side:THREE.DoubleSide,
            transparent:true,
            opacity:0.5
        })
        group.children.forEach(item=>{
            if ( item.name.includes('tube')) {
                item.material = tubeMtl;
                return;
            }
            if ( item.name.includes('windLeave') ) {
                windLeaves.push(item);
                item.material = mtl2;
                return;
            }
            if ( item.name === 'ground' ) {
                // item.material = new THREE.MeshPhysicalMaterial({
                //     transparent:true,
                //     opacity:0.25,
                //     side:THREE.DoubleSide,
                //     transmission:0.95,
                //     color:0x0e4e77
                // })
                item.material = new THREE.MeshBasicMaterial({
                    side:THREE.DoubleSide,
                    map:tex2,
                    transparent:true,
                    opacity:0.6
                    
                })
                return;
            }
            if ( item.name.includes('bump') ) {
                item.material = mtl2;
            } else {
                item.material = mtl1;
            }
        })
        this.canvasScene.add(group);
    }
    setAlarm(mesh){
        // 获取每个模型的空间大小
        let box = new THREE.Box3();
        let infoDom = document.getElementsByClassName(style['info-container'] + ' ' + style['alarm'])[0];
        console.log(infoDom);
        box.expandByObject(mesh);
        var height = box.max.y - box.min.y;
        let vector = new THREE.Vector3(mesh.position.x, mesh.position.y + height/2, mesh.position.z);
        let topVector = new THREE.Vector3(mesh.position.x, mesh.position.y + height/2, mesh.position.z );
        let bottomVector = new THREE.Vector3(mesh.position.x, mesh.position.y - height/2, mesh.position.z );
        vector.project(this.camera);
        let newVector = new THREE.Vector2();
        newVector.x = ( 0.5 + vector.x / 2 ) * this.sizes.width;
        newVector.y = ( 0.5 - vector.y / 2 ) * this.sizes.height;
        console.log(vector, newVector);
        if ( infoDom ) {
            infoDom.style.display = 'block';
            infoDom.style.left = newVector.x + 'px';
            infoDom.style.bottom = newVector.y + 'px';
            infoDom.style.transform = 'translateX(-50%)';
        }
        mesh.alarm = true;
        this.renderer.outlinePass.visibleEdgeColor.set('#ff0000'); // 设置显示的颜色
        this.renderer.outlinePass.selectedObjects = [mesh];

        setTimeout(()=>{
            if ( infoDom ) {
                infoDom.style.display = 'none';
            }
            this.renderer.outlinePass.selectedObjects = [];
        },5000)
    }
    handleMtl(mesh){
        mesh.castShadow = true;
        // mesh.material = new THREE.MeshBasicMaterial({
        //     transparent:true,
        //     color:new THREE.Color(Math.random() * 1, Math.random() * 1, Math.random() * 1),
        //     opacity:0.5,
        //     side:THREE.DoubleSide,
        //     // gltf格式中会保留blender 布尔操作的运算结果，所以表现为Group，子集为多个Mesh，而blender中合并模型是将多个Mesh强制合并为一个Mesh，所以表现为Mesh类型
        // })
        mesh.material = new THREE.MeshStandardMaterial({
            color:0x3068e1,
            roughness:0.1,
            metalness:0.1,
            envMap:envMap.texture,      
        });
        if ( mesh.name === 'waterCollector' ) {
            let vec3 = new THREE.Vector3();
            console.log('a');
            mesh.updateMatrixWorld();
            vec3.setFromMatrixPosition(mesh.matrixWorld);
            // vec3.project(this.camera);
            // vec3.x = ( 0.5 + vec3.x * 0.5 ) * this.sizes.width ;
            // vec3.y = ( 0.5 - vec3.y * 0.5 ) * this.sizes.height ;
            console.log(vec3);
        }
        if ( mesh.name.includes('扇叶')){
            mesh.material.color.set(0xfaf9f8);
        }
        // 管道材质
        if ( mesh.name.includes('frozen-mach')) {             
            mesh.material.color.set(0x3068e1);
        }
        if ( mesh.name === 'waterDispatcher') {
            mesh.material.color.set(0x3068e1);
        }
        if ( mesh.name === 'waterCollector') {
            mesh.material.color.set(0x3ae0e9);
        }
        // 管道材质
        if ( mesh.name.includes('tube')){
            // mesh.material.transparent = true;
            // mesh.material.opacity = 0.8;
            let strArr = mesh.name.split('-');
            let color = strArr[1];
            if ( color === 'blue' ) {
                mesh.material.color.set(0x3068e1);
            }
            if ( color === 'cyan') {
                mesh.material.color.set(0x3ae0e9);
            }
            if ( color === 'green') {
                mesh.material.color.set(0x44da19);
            }
        }
        // 地面材质
        if ( mesh.name === 'ground' ) {
            mesh.material.transparent = true;
            mesh.material.opacity = 0.4;
            mesh.material.color.set(0x303539);
            mesh.receiveShadow = true;     
        }
    }
    setAnimation(){
        this.mixer = new THREE.AnimationMixer(this.room.scene);
        // this.swim = this.mixer.clipAction(this.room.animations[0]);
        // this.swim.play();
    }
    
    update(){
        // 乘上一个影响因子，控制动画帧率
        // let factor = 0.001;
        // this.mixer.update(this.time.delta * factor );
        windLeaves.forEach(mesh=>{
            mesh.rotation.y += 0.01;
        });
        // if ( this.resources.items.flow ) {
        //     this.resources.items.flow.offset.y += 0.001;
        // }
    }
}